"""
@filename=main.py
@version=0.1.0.20240326
@author=amnotgcs
@createTime=20240326 12:39
@lastModifiedTime=20240326 12:39
@description=获取图灵网站的可兑换样书信息
@web.url=https://www.ituring.com.cn/book
"""

import json
from pathlib import Path

import requests

from configs import Config as config
from configs import logger

SEARCH_API = "https://api.ituring.com.cn/api/Search/Advanced"  # 图灵网站图书搜索API
COVER_API = "https://file.ituring.com.cn/LargeCover"  # 图书封面API
HEADER = {
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6,zh-TW;q=0.5",
    "Referer": "https://www.ituring.com.cn/",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:123.0) Gecko/20100101 Firefox/123.0",
}
BOOK_INFO_FILENAME = f"books_{config.today_hhmmss}.json"  # 图书信息文件名
COVER_FOLDER = Path("images")  # 图书封面文件夹
COVER_FOLDER.mkdir(exist_ok=True)  # 确保 IMAGE_PATH 文件夹存在


def get_exchengeable_books() -> dict:
    """获取所有可兑换图书"""
    book_info_list = []
    pyload = {
        "categoryId": 0,
        "sort": "new",
        "page": 1,
        "name": "",
        "edition": 1,
        "isGiftBook": True,
    }
    while True:
        book_info = requests.post(
            SEARCH_API, json=pyload, headers=HEADER, timeout=3
        ).json()
        book_info_list.extend(book_info.get("bookItems"))
        page_number = book_info.get("pagination").get("pageNumber")
        page_count = book_info.get("pagination").get("pageCount")
        current_page_count = len(book_info.get("bookItems"))
        total_count = book_info.get("pagination").get("totalItemCount")
        logger.info(
            f"已获取第[{page_number}]页,数量:[{page_count}],"
            f"总进度:[{(page_number - 1) * page_count + current_page_count}/{total_count}]"
        )
        if book_info.get("pagination").get("isLastPage"):
            break
        pyload["page"] += 1
    return book_info_list


def book_info_persistence(book_info_list: list, filename: str = None) -> None:
    """
    图书信息数据持久化

    Parameters
    ----------
    book_info_list : list
        图书信息列表
    filename : str
        图书保存文件名
    """
    filename = filename or BOOK_INFO_FILENAME
    with Path(filename).open("w", encoding="utf8") as file:
        json.dump(book_info_list, file, ensure_ascii=False, indent=4)


def retrieve_book_cover(book_info_list: list, update: bool = False) -> None:
    """
    下载图书封面

    Parameters
    ----------
    book_info_list : list
        图书信息列表
    update : bool
        本地已有图片时是否更新，默认为False不更新
    """
    for book in book_info_list:
        cover_key = book.get("coverKey")
        filename = COVER_FOLDER / f"{cover_key}.jpg"
        if filename.exists() and not update:
            logger.info(f"封面[{filename.as_posix()}]已经存在，不更新")
            continue
        cover = requests.get(f"{COVER_API}/{cover_key}", headers=HEADER, timeout=3)
        filename.write_bytes(cover.content)
        book_name = book.get("name")
        logger.info(f"[{book_name}]的封面已保存[{filename.as_posix()}]")


if __name__ == "__main__":
    book_info_list = get_exchengeable_books()
    book_info_persistence(book_info_list)
    retrieve_book_cover(book_info_list)
